<template>
  <!-- 头部 -->
  <div class="component-common-header-home">
    <div class="content">
      <router-link
        to="/"
        class="logo"
      >
        <img
          v-if="webConfigData.pcLogoImgText"
          class="logo-img"
          :src="webConfigData.pcLogoImgText"
        >
      </router-link>
      <div class="search-msg">
        <input
          v-model="keyword"
          type="text"
          class="search-input"
          :placeholder="$t('commonHead.tips2')"
          :readonly="searchInputReadonly"
          autocomplete="off"
          @keyup.enter="searchKeyword"
          @focus="searchInputReadonly=false"
          @blur="searchInputReadonly=true"
        >
        <div
          class="search-type-box disable-check-text"
          @click="switchSearchType()"
        >
          <span class="search-type">{{ searchType === 1 ? $t('commonHead.goods') : $t('commonHead.shop') }}</span>
          <img
            src="@/assets/images/switch.png"
            class="switch-icon"
            alt=""
          >
        </div>
        <input
          type="submit"
          class="search-btn"
          :value="$t('commonHead.search')"
          @click="searchKeyword"
        >
        <div class="hot-word">
          <div class="con">
            <span
              v-for="(item, index) in hotSearchList"
              :key="index"
              class="item"
              @click="searchHotKeyword(item.content)"
            >{{ item.title }}</span>
          </div>
        </div>
      </div>
      <div
        class="cart-btn"
        @click="toMyCartPage"
      >
        {{ $t('commonHead.shoppingCart') }}({{ totalCartCount >= 1000 ? '999+' : totalCartCount || 0 }})
      </div>
    </div>
    <div class="menu">
      <div
        class="item prod-sort"
        @mouseenter="enterOrLeaveCategoryFrame(true)"
        @mouseleave="enterOrLeaveCategoryFrame(false)"
        @click="showClassifieds"
      >
        {{ $t('commonHead.tips3') }}
        <div class="sort-icon">
          <img src="@/assets/images/sort-more.png">
        </div>
        <!-- 分类目录 -->
        <classifieds
          v-if="isHoverCategoryPart"
          :category-list="categoryList"
          :sub-category-list="subCategoryList"
          :featured-brands="featuredBrands"
          :in-shop="false"
          class="classifieds"
          @switch-sub-category="getProdList"
          @to-prod-list="toProdList"
          @to-search-brand="toSearchBrand"
        />
      </div>
      <router-link
        to="/"
        :class="['item',$route.path == '/'?'item-on':'']"
      >
        {{ $t('commonHead.home') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/list' && $route.query.st == 0 ?'item-on':'']"
        to="/list?st=0"
      >
        {{ $t('commonHead.productList') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/list' && $route.query.st == 1 ?'item-on':'']"
        to="/list?st=1"
      >
        {{ $t('commonHead.newProducts') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/special-discount'?'item-on':'']"
        to="/special-discount"
      >
        {{ $t('commonHead.limitedTimeOffer') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/group-buy'?'item-on':'']"
        to="/group-buy"
      >
        {{ $t('commonHead.groupDiscount') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/flash-sale'?'item-on':'']"
        to="/flash-sale"
      >
        {{ $t('commonHead.spikeSpecial') }}
      </router-link>
      <router-link
        :class="['item',$route.path == '/coupons'?'item-on':'']"
        to="/coupons"
      >
        {{ $t('commonHead.voucherCenter') }}
      </router-link>
    </div>
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import classifieds from '@/components/classifieds/index.vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const featuredBrands = ref([]) // 推荐品牌
let searchType = ref(1) // 搜索类型 1:商品 2:店铺
const hotSearchList = ref([]) // 热搜列表
const webConfigStore = useWebConfigStore()
const webConfigData = computed(() => webConfigStore.pcConfig)
const searchInputReadonly = ref(true) // 搜索栏的input框的 只读属性，默认开启，防止浏览器回填
const cartNumberStore = useCartNumberStore()

const totalCartCount = computed(() => {
  if (!Cookie.get('bbcToken')) {
    return 0
  } else {
    return cartNumberStore.cartNumbers
  }
})
watch(searchType.value, (val) => {
  const searchTypeTemp = val === 1 ? 1 : 2
  getHotSearchList(searchTypeTemp)
})
const keyword = ref('') // 关键词
watch(() => route, () => {
  keyword.value = route.query.pn || route.query.shopName || ''
  if (route.path !== '/shopList' && route.path !== '/list') {
    keyword.value = ''
  }
  if (route.path === '/list') {
    searchType = 1
  }
  if (route.path === '/shopList') {
    searchType = 2
  }
})

onMounted(() => {
  if (route.path === '/list') {
    searchType = 1
    keyword.value = route.query.pn
  }
  if (route.path === '/shopList') {
    searchType = 2
    keyword.value = route.query.shopName
  }
  getHotSearchList(1) // 获取热搜列表
  queryCategoryData() // 查询分类列表
})

/**
 * 移入移出全部分类项
 * @param {Number} isHover true:移入 false:移出
 */
const isHoverCategoryPart = ref(false) // 是否展示全部类别
const enterOrLeaveCategoryFrame = (isHover) => {
  isHoverCategoryPart.value = isHover
}

/**
 * 获取热搜列表
 * @param {Number} type 1:商品 2:店铺
 */
const getHotSearchList = (type) => {
  http.get('/search/hotSearch', {
    params: {
      type
    }
  }).then(({ data }) => {
    hotSearchList.value = data.slice(0, 4)
  })
}

/**
 * 搜索关键词
 */
const searchKeyword = () => {
  if (!keyword.value || !keyword.value.trim()) {
    ElMessage.warning({
      message: $t('index.keyWordNoNull'),
      type: 'error',
      duration: 1000
    })
    return
  }
  // 1:跳转到商品搜索列表页 2:跳转到店铺列表
  if (searchType === 1) {
    toSearchListPage()
  } else {
    toShopListPage()
  }
  // keyword = null
}

/**
 * 搜索热搜关键词
 * @param hotWord 热搜词语
 */
const searchHotKeyword = (hotWord) => {
  keyword.value = hotWord
  if (searchType === 1) {
    toSearchListPage()
  } else {
    toShopListPage()
  }
}

/**
 * 获取一级分类列表(获取平台端全部分类)
 */
const categoryList = ref([]) // 分类列表（一级分类）
const queryCategoryData = () => {
  http.get('/category/categoryInfo?parentId=' + '', {
  }).then(({ data }) => {
    if (!data) return
    const classifyList = data.categoryInfo
    categoryList.value = classifyList || []
    getProdList(classifyList[0].categoryId)
  })
}

/**
 * 加载子分类列表
 */
const subCategoryList = ref([]) // 二级分类
const getProdList = (categoryId) => {
  http.get('/category/categoryInfo?parentId=' + categoryId)
    .then(({ data }) => {
      if (data) subCategoryList.value = data.categoryInfo
    })
}

/**
 * 切换搜索类型
 */
const switchSearchType = () => {
  searchType = searchType === 1 ? 2 : 1
}

/**
 * 跳转子分类商品页面 */
const toProdList = (parentId, categoryId, thCategoryId, st) => {
  router.push({
    path: '/list',
    query: {
      cpid: parentId,
      cid: categoryId,
      thCid: thCategoryId,
      st
    }
  })
}
/**
 * 搜索品牌下相关商品
 */
const toSearchBrand = (brandId, name) => {
  router.push({ path: `/list?bid=${brandId}&bName=${name}` })
}

// 跳转到购物车
const toMyCartPage = () => {
  router.push({ path: '/cart' })
}

/**
 * 跳转到列表页
 */
const toSearchListPage = () => {
  const searchTerms = keyword.value.trim() // 去除字符串的头尾空格
  if (!searchTerms) {
    ElMessage({
      message: $t('commonHead.productNameCannotBeEmpty'),
      type: 'error',
      duration: 1000
    })
    return
  }
  // 跳转到商品列表页
  router.push({ path: '/list?pn=' + searchTerms })
}

/**
 * 跳转到店铺列表页
 */
const toShopListPage = () => {
  const searchTerms = keyword.value.trim() // 去除字符串的头尾空格

  if (!searchTerms) {
    ElMessage({
      message: $t('commonHead.storeNameCannotBeEmpty'),
      type: 'error',
      duration: 1000
    })
    return
  }
  // 跳转到店铺列表页
  router.push({ path: '/shopList?shopName=' + searchTerms })
}

</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
